var CONFIG = require('../config/config').Config;
var logger = require('../config/logger');
var mongoose = require('mongoose');

// bootstap db connection
var db = mongoose.connect(CONFIG.DBURL);
logger.info("mongo connected to " + CONFIG.DBURL);

// exit on db connection error
mongoose.connection.on('error', function (err) {
  logger.error("mongodb error: " + err);
  process.exit(1);
});

// retry 3 times on db connection lost
var attempt = 1;

mongoose.connection.on('disconnected', function() {
  if (attempt < 3) {
    logger.error("mongodb disconnected, trying to reconnect..");
    logger.info("mongodb reconnect, attempt num " + attempt);
    attempt += 1
    db = mongoose.connect(CONFIG.DBURL);
  } else {
    logger.error("mongodb disconnect, giving up!");
  }
});

exports.User = (require("./user")).User;
exports.Article = (require("./article")).Article;
exports.Tag = (require("./tag")).Tag;
